﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using PMS.Core.Configuration.CommonEnumConfigs;
using PMS.Core.Infrastructure;
using PMS.Core.Utils;
using PMS.Services.Utils;
using PMS.Services.Utils.Security;
using System;

namespace PMS.Web.Framework.Mvc.Filters
{
    /// <summary>
    /// 对后台系统模块进行了角色授权后，校验模块是否有操作权限
    /// </summary>
    public class ModulePermissionAttribute : ActionFilterAttribute
    {
        #region Ctor
        /// <summary>
        /// Create instance of the filter attribute
        /// </summary>
        public ModulePermissionAttribute() : base()
        {
        }

        #endregion

        #region Methods
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (context == null)
                throw new ArgumentNullException(nameof(context));
            try
            {
                if (!(context.ActionArguments.TryGetValue("hashId", out object value)
                                && value is string hashId))
                    throw new PMSException("Invalid Argument of hashId", SystemLogLevel.Error);
                
                var permissionService = EngineContext.Current.Resolve<IPermissionService>();
                if (!permissionService.AdminAuthorize(hashId))
                {
                    var webHelper = EngineContext.Current.Resolve<IWebHelper>();
                    context.HttpContext.Response.StatusCode = 403;
                    context.Result = new RedirectToActionResult("AccessDenied", "Common", new { pageUrl = webHelper.GetRawUrl(context.HttpContext.Request) });
                }
                return;
            }
            catch (Exception ex)
            {
                context.HttpContext.Response.StatusCode = 400;
                context.Result = new ContentResult()
                {
                    Content = ex.Message
                };
                return;
            }
        }
        #endregion
    }
}
